<?php

declare(strict_types=1);

namespace App\Command;

use App\Components\System\HttpClient;
use App\Exception\ServiceException;
use App\Utils\AmountUtils;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\Stringable\Str;
use Psr\Container\ContainerInterface;
use Exception;
#[Command]
class TestWuCommand extends HyperfCommand
{

    /**
     * 公钥字符串
     * @var string
     */
    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('test:wu');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('Hyperf Demo Command');
    }

    function padding($src, $len) {
        $srcLength = strlen($src);
        $paddingLength = $len - ($srcLength % $len);

        if ($paddingLength == $len) {
            return $src;
        }
        return $src . str_repeat("\0", $paddingLength);
    }

    public function handle()
    {

        $amount = AmountUtils::fenToYuan(2536);

        var_dump($amount);

//        var_dump(password_hash(trim('123456'),PASSWORD_DEFAULT));

//        $key = "0DO2yfIrpmwWygmX";//Str::random();
//        $msgId = Str::random(32);
//        $headerData = [
//            'msgId' => $msgId,
//            'merchNo' => 'B00001004',
//            'txCode' => 'ZLPAY.CBPS.Q01005',
//            'signNo' => '1061319076',
//            'Content-type' => 'application/json;charset=UTF-8',
//            'version' => '1.1.1',
//            'encrp' => '1',
//            'encrpNo' => '1055490595',
//            'timestamp' => date('YmdHis'),
//        ];
//        /**
//         * 请求参数
//         */
//        $requestData = ['code' => 'USD'];
//        $jsonData = $this->sm4Encode($requestData,$key);
//        $bodyStr = $this->getSignAndSecret($key,$jsonData);
//        $bodyStr2 = $this->encodeRequest($key,$requestData);
//
//
//
//
//        $response = (new HttpClient($headerData,10))->postRaw("https://gatewaytest.zqpay.com", $bodyStr2);
//        $responseBody = $response->getBody()->getContents();
//
//        $bodyData = json_decode($responseBody,true);
//
//        $decodeKey = $this->getDecodeKey($bodyData['secret']);
//        $contentsData = $this->sm4Decode($decodeKey,$bodyData['data']);
//        $contents = json_decode($contentsData,true);

//        print_r($contents);
    }

    public function encodeRequest(string $key ,array $params)
    {
        $javaPath = "/usr/bin/java";
        $jarPath = BASE_PATH."/storage/java/LZ_PAY-1.0-SNAPSHOT.jar";
        $bodyStr = json_encode($params,JSON_UNESCAPED_UNICODE);

        $bodyStr = addslashes($bodyStr);
        $response = shell_exec("$javaPath -jar $jarPath encode {$key} {$bodyStr}");
        if(empty($response)) throw new ServiceException("签名加密错误");
        return trim($response);
    }



    public function sftp()
    {
        //sftp信息
        //账号：B00001004
        //密码：B00001004123
        $connection = ssh2_connect('gatewaytest.zqpay.com', 22);
        if (!$connection) {
            throw new ServiceException("sftp链接失败");
        }

        $localFile = BASE_PATH.'/runtime/办公照片.jpg';

        $remoteDir = '/B00001004/ATTACHMENT/'.date("Ym").'/';

        var_dump($remoteDir);
        // 认证方式1：密码认证
        if (!ssh2_auth_password($connection, "B00001004", "B00001004123")) {

            throw new ServiceException("sftp服务认证失败");
        }

        // 初始化SFTP
        $sftp = ssh2_sftp($connection);
        if (!$sftp) {
            throw new ServiceException("无法初始化SFTP子系统");
        }
        // 远程文件路径
        $remoteFile = "ssh2.sftp://{$sftp}{$remoteDir}" . basename($localFile);


        var_dump($remoteFile);
        /**
         * 文件不存在自动创建
         */
        if (!file_exists("ssh2.sftp://{$sftp}{$remoteDir}")) {
            $res = ssh2_sftp_mkdir($sftp, $remoteDir, 0755, true);
            var_dump($res);
        }

//        $localStream = fopen($localFile, 'rb');
//        $remoteStream = fopen("ssh2.sftp://{$sftp}{$remoteDir}" . basename($localFile), 'wb');
//
//        if (!$localStream || !$remoteStream) {
//            die("无法打开文件流");
//        }
//
//        while (!feof($localStream)) {
//            $chunk = fread($localStream, 8192); // 8KB分块
//            fwrite($remoteStream, $chunk);
//        }
//
//        fclose($localStream);
//        fclose($remoteStream);


        unset($sftp);
        ssh2_disconnect($connection);

        $this->info("附件上传成功");

    }



    public function verfiySign(string $sign,string $bodyData)
    {
        $javaPath = "/usr/bin/java";
        $jarPath = BASE_PATH."/storage/java_secr/LZ_PAY-1.0-SNAPSHOT.jar";

        $res = trim(shell_exec("$javaPath -jar $jarPath verify {$sign} {$bodyData}"));

        if($res != 'true') throw new ServiceException("签名验证失败");

    }

    public function getDecodeKey(string $secretData)
    {
        $javaPath = "/usr/bin/java";
        $jarPath = BASE_PATH."/storage/java_secr/LZ_PAY-1.0-SNAPSHOT.jar";

        $decodeStr = shell_exec("$javaPath -jar $jarPath decode {$secretData}");
        if(empty($decodeStr)) throw new ServiceException("获取对称密钥失败");
        return trim($decodeStr);
    }

    /**
     * 签名与加密
     * @param string $key
     * @param string $jsonData
     * @return string|null
     */
    public function getSignAndSecret(string $key,string $jsonData)
    {
        $javaPath = "/usr/bin/java";
        $jarPath = BASE_PATH."/storage/java_secr/LZ_PAY-1.0-SNAPSHOT.jar";
        $response = shell_exec("$javaPath -jar $jarPath encode {$key} {$jsonData}");
        if(empty($response)) throw new ServiceException("签名加密错误");
        return trim($response);

    }

    private function sm4Decode(string $key,string $bodyData)
    {
        $data = base64_decode($bodyData);
        // 添加填充
        $blockSize = 16; // SM4 块大小固定为16字节
        $data = $this->padding($data, $blockSize);
        if (in_array('sm4-ecb', openssl_get_cipher_methods())) {
            $encrypted = openssl_decrypt($data, 'sm4-ecb', $key, OPENSSL_NO_PADDING);
            return trim($encrypted);
        }else{
            throw new ServiceException("openssl not find sm4-ecb");
        }
    }


    private function sm4Encode(array $requestData,string $key)
    {
        $data = json_encode($requestData,JSON_UNESCAPED_UNICODE);

        // 添加填充
        $blockSize = 16; // SM4 块大小固定为16字节
        $data = $this->padding($data, $blockSize);
        if (in_array('sm4-ecb', openssl_get_cipher_methods())) {
            $encrypted = openssl_encrypt($data, 'sm4-ecb', $key, OPENSSL_NO_PADDING);
            $encode = base64_encode($encrypted);
            return $encode;
        }else{
            throw new ServiceException("openssl not find sm4-ecb");
        }
    }
}
